// main.js - 主要的JavaScript文件

// 移动端菜单切换
const menuToggle = document.getElementById('menu-toggle');
const mobileMenu = document.getElementById('mobile-menu');

menuToggle.addEventListener('click', () => {
    mobileMenu.classList.toggle('hidden');
    // 切换图标
    const icon = menuToggle.querySelector('i');
    if (icon.classList.contains('fa-bars')) {
        icon.classList.replace('fa-bars', 'fa-times');
    } else {
        icon.classList.replace('fa-times', 'fa-bars');
    }
});

// 导航栏滚动效果
const navbar = document.getElementById('navbar');

window.addEventListener('scroll', () => {
    if (window.scrollY > 50) {
        navbar.classList.add('py-2');
        navbar.classList.remove('py-4');
        navbar.classList.add('shadow-lg');
    } else {
        navbar.classList.add('py-4');
        navbar.classList.remove('py-2');
        navbar.classList.remove('shadow-lg');
    }
});

// 平滑滚动
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        
        // 如果是移动端菜单，点击后关闭菜单
        if (!mobileMenu.classList.contains('hidden')) {
            mobileMenu.classList.add('hidden');
            const icon = menuToggle.querySelector('i');
            icon.classList.replace('fa-times', 'fa-bars');
        }
        
        const targetId = this.getAttribute('href');
        if (targetId === '#') return;
        
        const targetElement = document.querySelector(targetId);
        if (targetElement) {
            targetElement.scrollIntoView({
                behavior: 'smooth'
            });
        }
    });
});

// 黑夜模式切换功能
const htmlElement = document.documentElement;
const themeToggle = document.getElementById('theme-toggle');
const mobileThemeToggle = document.getElementById('mobile-theme-toggle');
const themeIcons = document.querySelectorAll('#theme-toggle i, #mobile-theme-toggle i');

// 检查用户偏好或保存的设置
function initTheme() {
    const savedTheme = localStorage.getItem('bookshelf-theme');
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    
    if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
        enableDarkMode();
    } else {
        disableDarkMode();
    }
}

// 启用黑夜模式
function enableDarkMode() {
    htmlElement.classList.add('dark');
    themeIcons.forEach(icon => {
        icon.classList.remove('fa-moon-o');
        icon.classList.add('fa-sun-o');
    });
    localStorage.setItem('bookshelf-theme', 'dark');
}

// 禁用黑夜模式
function disableDarkMode() {
    htmlElement.classList.remove('dark');
    themeIcons.forEach(icon => {
        icon.classList.remove('fa-sun-o');
        icon.classList.add('fa-moon-o');
    });
    localStorage.setItem('bookshelf-theme', 'light');
}

// 切换黑夜模式
function toggleDarkMode() {
    if (htmlElement.classList.contains('dark')) {
        disableDarkMode();
    } else {
        enableDarkMode();
    }
}



// 监听主题切换按钮
if (themeToggle) {
    themeToggle.addEventListener('click', toggleDarkMode);
}
if (mobileThemeToggle) {
    mobileThemeToggle.addEventListener('click', toggleDarkMode);
}

// 监听系统主题变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
    if (!localStorage.getItem('bookshelf-theme')) {
        if (e.matches) {
            enableDarkMode();
        } else {
            disableDarkMode();
        }
    }
});

// 返回顶部按钮
window.addEventListener('DOMContentLoaded', () => {
    // 获取按钮元素
    const backToTopButton = document.getElementById('back-to-top');
    
    // 确保按钮元素存在
    if (backToTopButton) {
        console.log('返回顶部按钮元素已找到');
        
        // 滚动检测函数，增强兼容性
        function handleScroll() {
            // 获取当前滚动位置（兼容不同浏览器）
            const scrollPosition = window.scrollY || document.documentElement.scrollTop || document.body.scrollTop;
            console.log('当前滚动位置:', scrollPosition);
            
            // 当滚动超过100像素时显示按钮，否则隐藏
            if (scrollPosition > 100) {
                // 显示按钮并添加动画效果
                backToTopButton.style.display = 'flex';
                setTimeout(() => {
                    backToTopButton.style.opacity = '1';
                    backToTopButton.style.transform = 'translateY(0)';
                }, 10);
                console.log('按钮已显示');
            } else {
                // 隐藏按钮并添加动画效果
                backToTopButton.style.opacity = '0';
                backToTopButton.style.transform = 'translateY(10px)';
                setTimeout(() => {
                    if (window.scrollY <= 100) {
                        backToTopButton.style.display = 'none';
                    }
                }, 300);
                console.log('按钮已隐藏');
            }
        }
        
        // 立即执行一次滚动检测，确保初始状态正确
        handleScroll();
        
        // 添加滚动事件监听器，使用节流函数优化性能
        let scrollTimeout;
        window.addEventListener('scroll', () => {
            clearTimeout(scrollTimeout);
            scrollTimeout = setTimeout(handleScroll, 50);
        });
        
        // 点击按钮返回顶部
        backToTopButton.addEventListener('click', function() {
            console.log('按钮被点击，返回顶部');
            
            // 平滑滚动到顶部（兼容写法）
            try {
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            } catch (e) {
                console.error('平滑滚动失败，使用降级方案:', e);
                // 降级方案，直接滚动
                window.scrollTo(0, 0);
            }
        });
    } else {
        console.error('未找到返回顶部按钮元素，请检查HTML中的id属性');
    }
});
// 初始化主题
initTheme();
